#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main()
{
  struct sockaddr_in	servaddr;
  struct sockaddr_in	from;
  int			sockfd = 0;
  int			fromsize = sizeof (from);
  char			buff[1024];
  char			*file_name = NULL;
  FILE			*f;

  memset(&servaddr, 0, sizeof(servaddr));
  memset(&from, 0, sizeof(from));
  sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sockfd == -1)
  {
    perror("socket()");
    exit(errno);
  }

  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(33333);
  if (bind(sockfd, (struct sockaddr *) &servaddr, sizeof (struct sockaddr_in))== -1)
    {
      perror("bind()");
      exit(errno);
    }

  if (recvfrom(sockfd, buff, sizeof(buff), 0, (struct sockaddr *) &from, &fromsize) < 0)
    {
      perror("recvfrom()");
      exit(errno);
    }
  printf("%s, %i\n", buff, strlen(buff));
  extract_header(buff); //verif a faire
  printf("avant buf : %s\n", buff);
  file_name = extract_fheader(buff);
  printf("filename: %s\n", file_name);
  f = fopen(file_name, "w");
  if (f == NULL)
    {
      perror("fopen()");
      exit(errno);
    }
  //free(file_name);
  while (strcmp(buff, "-1\0") != 0)
  {
    fwrite(buff + 1, 1, strlen(buff), f); //strlen(buff) ne marchera pas avec binaire
    //fputs(buff, f);
    memset(buff, '\0', sizeof(buff));
  if (recvfrom(sockfd, buff, sizeof(buff), 0, (struct sockaddr *) &from, &fromsize) < 0)
    {
      perror("recvfrom()");
      exit(errno);
    }
  printf("[%s], %i\n", buff, sizeof(buff));
  }

  /*buff[0] = 'm';
  buff[1] = 'a';
  buff[2] = 'n';
  buff[3] = 'g';
  buff[4] = 'e';
  buff[5] = 'r';
  buff[6] = '?';
  buff[7] = 0;*/
  /*fromsize = sizeof (from); //temp
  if(sendto(sockfd, buff, strlen(buff), 0, (struct sockaddr *) &from, fromsize) < 0)
    {
      perror("sendto()");
      exit(errno);
    }*/
  fflush(f);
  fclose(f);
  close(sockfd);
}
